#include "abscences.h"
#include "mainwindow.h"


bool editMode=false;
bool changed=false;
int curRow=-1,curCol=-1;
const int jourOuvrable=26;
QList <QString> causes;
QSqlQuery op;
QString monthStr=QString("%1").arg(QDate::currentDate().month());;
QString yearStr=QString("%1").arg(QDate::currentDate().year());

QString tableSal=monthStr+'-'+yearStr;
QString stTable="CREATE TABLE `paye`.`";
QString endTable="` (`cin` INT( 11 ) NOT NULL , `salBase` DECIMAL( 7, 3 ) NOT NULL , `retenu` DECIMAL( 7, 3 ) NOT NULL , `prime` DECIMAL( 7, 3 ) NOT NULL , `salFinal` DECIMAL( 7, 3 ) NOT NULL , `notes` TEXT NOT NULL , PRIMARY KEY(`cin`) ) ENGINE = MYISAM ";


Dialog::Dialog(QWidget *parent ): QDialog(parent)
{
    setupUi(this);
    
    absTable->setSortingEnabled(true);
    absTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    absTable->setColumnWidth(0,105);
    absTable->setColumnWidth(1,100);
    //absTable->setEditTriggers(QAbstractItemView::AllEditTriggers);
    //connect(absTable, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(changeSelection(int,int)));
    /// link between a subclass of QDateEdit and calendar view
    connect(calendarWidget, SIGNAL(activated(QDate)),this,SLOT(setDate(QDate)));
    //nbrAbsSB->setValue(calcAbsNbr());
    causes<<"Maladie"<<"Inconnue"<<"Autre";
    QCompleter *causeComp= new QCompleter(causes, this);
    causeComp->setCompletionMode(QCompleter::InlineCompletion);
    causeComp->setCaseSensitivity(Qt::CaseInsensitive);
    raisonLE->setCompleter(causeComp);
    
}


void Dialog::setCin(QString curCin,QString name,double baseSal){
    curcin=curCin;
    curName=name;
    curSal=baseSal;
    baseSalSB->setValue(baseSal);
    nameLE->setText(curName);
    updateSal();
}

void Dialog::calcJour(double baseSal){
    jourSalSB->setValue(baseSal/jourOuvrable);
}

void Dialog::save(){
    /// We have to make sure that the table of the current month is already created
    if (changed) {
        saveChanges();
    }
    editMode=false;
    accept();
}

void Dialog::saveChanges(){
    QString sal=QString("%1").arg(curSal);
    
    op=QSqlQuery();

    /// @bug : have to check niot create directly
    if(!op.exec( stTable+tableSal+endTable )){

        qDebug()<<"could not create the table of month"+tableSal<<op.lastError().text();
    }

//qDebug()<<("UPDATE `paye`.`"+tableSal+"` SET `cin`="+curcin+" ,`salBase`="+sal+" ,`retenu`="+costSB->text()+" ,`prime`="+primeSB->text()+" ,`salFinal`="+salSB->text()+" ,`notes`='"+notes->toPlainText()+"' WHERE `cin`='"+curcin+"')");
    if(!op.exec("INSERT INTO `paye`.`"+tableSal+"` (`cin`, `salBase`, `retenu`, `prime`, `salFinal`, `notes`) VALUES ('"+curcin+"','"+sal+"','"+costSB->text()+"','"+primeSB->text()+"','"+salSB->text()+"','"+notes->toPlainText()+"')")){
        if (op.lastError().text().contains("Duplicate")){
            if (!op.exec("UPDATE `paye`.`"+tableSal+"` SET `cin`="+curcin+" ,`salBase`="+sal+" ,`retenu`="+costSB->text()+" ,`prime`="+primeSB->text()+" ,`salFinal`="+salSB->text()+" ,`notes`='"+notes->toPlainText()+"' WHERE `cin`='"+curcin+"'")){
                QMessageBox::critical(0,"Opération non réalisée","Impossible de mettre à jour :\n"+op.lastError().text(),QMessageBox::Ok);
            }
        }
    }
    //else{
      //  QMessageBox::critical(0,"Opération non réalisée","Impossible d'ajouter dans la table de paye:\n"+op.lastError().text(),QMessageBox::Ok);
        //return;
    //}
    
    /// Xwe also Insert/update the salsire in the salaire Table

    if(!op.exec("INSERT INTO `webpages`.`Salaires` (`cin`, `"+ monthStr+"`) VALUES ('"+curcin+"','"+salSB->text()+"')")){
        if (op.lastError().text().contains("Duplicate")){
            if (!op.exec("UPDATE `webpages`.`Salaires` SET `cin`="+curcin+" ,`"+monthStr+"`="+salSB->text()+" WHERE cin="+curcin)){
                QMessageBox::critical(0,"Opération non réalisée","Impossible de mettre à jour le salaire :\n"+op.lastError().text(),QMessageBox::Ok);
            }
        }
    }
    
    //else{
      //  QMessageBox::critical(0,"Opération non réalisée","Impossible d'ajouter le salaire :\n"+op.lastError().text(),QMessageBox::Ok);
        //return;
    //}
    
}


void Dialog::setMonth(const QDate & min, const QDate & max ){
    calendarWidget->setDateRange(min,max);
    curDate=max;
    monthStr=QString("%1").arg(curDate.month());
    tableSal=monthStr+'-'+yearStr;
    //qDebug()<<min<<max<<calendarWidget-> maximumDate()<<calendarWidget-> minimumDate();
}


void Dialog::setSel(QModelIndex ind){
    curRow=ind.row();
    absTable->selectRow(curRow);
}


void Dialog::hidePanel(){

    calLayout->parentWidget()->hide();
}
void Dialog::retrive(QList <QString> dates,QList <QString> raisons){
    QTableWidgetItem *newItem;

    
    
    /// To avoid adding unnessary rows we start from the
    for (int i=absTable->rowCount();i<dates.size();i++){
        
        absTable->insertRow( absTable->rowCount());
    }
    
    for (int i=0;i<dates.size();i++){
        
        newItem = new QTableWidgetItem(dates.at(i),0);
        newItem->setFlags(Qt::ItemIsSelectable);
        absTable->setItem(i, 0, newItem);
        newItem = new QTableWidgetItem(raisons.at(i),0);
        newItem->setFlags(Qt::ItemIsSelectable);
        absTable->setItem(i, 1, newItem);
        newItem = new QTableWidgetItem(duree.at(i),0);
        newItem->setFlags(Qt::ItemIsSelectable);
        absTable->setItem(i, 2, newItem);
    }
}

void Dialog::showAbs(int year, int month){
    /// we update the table to show


    tableSal=QString("%1-%2").arg(month).arg(year);

    QSqlQuery query("SELECT date, raison, journee FROM Absences where cin="+curcin);
    QString monthStr,yearStr,curMonth,curYear;
    curMonth.setNum(month);
    if (month <10) {
        curMonth.prepend("0");
    }
    curYear.setNum(year);
    
    
    dates.clear();
    raisons.clear();
    duree.clear();
    
    while (query.next()) {
        /// we chop the date to get the month and year
        monthStr=query.value(0).toString().section('-',1,1);
        yearStr= query.value(0).toString().section('-',0,0);
        /// We only display absences correpondign to currnet month
        //qDebug()<<curMonth<<monthStr;
        if ( monthStr==curMonth && yearStr==curYear){
            dates.append(query.value(0).toString());
            raisons.append(query.value(1).toString());
            duree.append(query.value(2).toString());
            //qDebug()<<"Affiche l'abscence"<<query.value(0).toString();
        }
    }
    clearTable();
    if (dates.size()!=0){
        retrive(dates,raisons);
    }

    primeSB->clear();
    notes->clear();
    salSB->clear();
    nbrAbsSB->clear();
    costSB->clear();

    query=QSqlQuery();
    
    if(!query.exec("SELECT retenu,prime,salFinal,notes FROM `paye`.`"+tableSal+"` WHERE cin="+curcin)){
        /// @todo: la siupposition que l'erreur vien t du fait que le table n'exiqte pas est un epu presombtusuese ?
        qDebug()<< "Salaire non calculé";
        return;
    }
    /// we move to the first field of the results
    query.next();

    /// si aucun enregistremnt n'est trouvé => salire non encore calculé!
    if (query.isValid()){

        costSB->setValue(query.value(0).toDouble());
        primeSB->setValue(query.value(1).toDouble());
        salSB->setValue(query.value(2).toDouble());
        notes->setText(query.value(3).toString());
    }

    nbrAbsSB->setValue(calcAbsNbr());
}


void Dialog::setEdit(bool state){
    editMode=state;
    /// Have to update the salary
    updateSal();
    if (state){
        editPB->setIcon(QIcon(":32x32/document-decrypt.png"));
        setMonth(QDate(QDate::currentDate().year(),curDate.month(),1),QDate(QDate::currentDate().year(),curDate.month(),curDate.daysInMonth()));        
    }
    else{
        
        editPB->setIcon(QIcon(":32x32/document-encrypt.png"));
        setMonth(QDate(2000,QDate::currentDate().month()+1,1),QDate(QDate::currentDate().year(),curDate.month(),curDate.daysInMonth()));
        if (changed) {
            
            saveChanges();
        }
    }
    absDate->setEnabled(state);
    raisonLE->setEnabled(state);
    /// The salary and abscences costs can't be changed manually ? A voir !
   // costSB->setEnabled(state);
    //salSB->setEnabled(state);
    primeSB->setEnabled(state);

    
}

double Dialog::calcAbsNbr(){
    double nbr=0;
     for (int i=0;i<absTable->rowCount();i++){
         if (absTable->item(i,2)->text()=="1")
             nbr++;
         else
             nbr=nbr+0.5;
    }

     return nbr;
}

void Dialog::setDate(QDate date){
    absDate->setDate(date);
}


void Dialog::addAbs() {
    if (!editMode){
        return;
        /// give the focus to the button
        
    }
    if( raisonLE->text().isEmpty() || absDate->date().toString("yyyy-MM-dd")=="2000-01-01"){
        QMessageBox::critical(0,"Impossible","Veuillez d'abord saisir la raison et la date de l'abscence",QMessageBox::Ok);
        return;
    }
    changed=true;
    QString J="1";
    if (demiRB->isChecked()) J="1/2";
    QString d=absDate->date().toString("yyyy-MM-dd");
    
    op=QSqlQuery();
    if(!op.exec("INSERT INTO Absences (cin, date,raison,journee) VALUES ('"+curcin+"','"+d+"','"+raisonLE->text()+"','"+J+"')")){
        if (op.lastError().text().contains("Duplicate"))
            QMessageBox::critical(0,"Opération non réalisée","Impossible d'ajouter l'abscence :\n Il existe déjà une autre absence dans la mm date",QMessageBox::Ok);
        else
            QMessageBox::critical(0,"Opération non réalisée","Impossible d'ajouter l'abscence :\n"+op.lastError().text(),QMessageBox::Ok);
        return;
    }
    
    calcAbsCost();
    
    absTable->insertRow( absTable->rowCount());
    
    QTableWidgetItem *newItem = new QTableWidgetItem(d,0);
    newItem->setFlags(Qt::ItemIsSelectable);
    absTable->setItem(absTable->rowCount()-1, 0, newItem);
    
    newItem = new QTableWidgetItem(raisonLE->text(),0);
    newItem->setFlags(Qt::ItemIsSelectable);
    absTable->setItem(absTable->rowCount()-1, 1, newItem);
    
    newItem = new QTableWidgetItem(J,0);
    newItem->setFlags(Qt::ItemIsSelectable);
    absTable->setItem(absTable->rowCount()-1, 2, newItem);
    
    nbrAbsSB->setValue(calcAbsNbr());
    
}

void Dialog::updateSal(double ret){
    if (!editMode) return;
    salSB->setValue(baseSalSB->value()-ret+primeSB->value());
    changed=true;
}

void Dialog::calcSal(){
    calcAbsCost();
    changed=true;
    salSB->setValue(baseSalSB->value()-costSB->value()+primeSB->value());
}

void Dialog::updateSal(){
    if (!editMode) return;
    calcAbsCost();
    changed=true;
    salSB->setValue(baseSalSB->value()-costSB->value()+primeSB->value());
}

void Dialog::calcAbsCost(){
    costSB->setValue(jourSalSB->value()*nbrAbsSB->value());
}

void Dialog::remAbs() {
    if (!editMode){
        return;
        /// give the focus to the button
        
    }
     if (absTable->rowCount()==0)
       return;


    QString date,raison;
    date=absTable->item(curRow,0)->text();
    raison=absTable->item(curRow,1)->text();
    
    op=QSqlQuery();
    if(!op.exec("DELETE FROM Absences WHERE cin="+curcin+" AND date='"+date+"'")){
        QMessageBox::critical(0,"Opération non réalisée","Impossible de supprimer l'abscence :\n"+op.lastError().text(),QMessageBox::Ok);
        return;
    }
    
    absTable->removeRow(curRow);

    nbrAbsSB->setValue(calcAbsNbr());
}

void Dialog::clearTable() {
    absTable->setRowCount(0);
}
